import React, { useEffect, useRef, useState } from 'react';
import { useMap, usePolygon } from '@uiw/react-baidu-map';
import { MapPoint } from '../pouch/models/City';
import { getCenter } from '../tooling/Map';

export interface BikeMapProp {
	polygon?: Array<MapPoint>;

	allowEdit: boolean;
	allowCreation: boolean;

	onContourUpdate?: (xs: MapPoint[]) => void;
}

export default function CityMap(props: BikeMapProp) {
	const [contour, setContour] = useState<MapPoint[]>([]);
	const divElm = useRef(null);

	const onMapClick = ({point}: { point: MapPoint }) => {
		if (props.allowCreation) {
			console.log(contour);
			if (contour.length < 2) {
				const updatedContour = contour.concat([point]);
				setContour(updatedContour);
			}
		}
		console.log(point);
	};

	const { setContainer, map, setCenter } = useMap({
		zoom: 10,
		center: '北京',
		widget: ['NavigationControl'],
		onClick: onMapClick
	});

	const {polygon, setPath} = usePolygon({
		map,
		enableEditing: props.allowEdit,
		path: contour,
		fillOpacity: 0.1,
		onLineUpdate: () => {
			if (props.onContourUpdate && polygon) {
				props.onContourUpdate(polygon?.getPath());
			}
		}
	});

	useEffect(() => {
		if (map && polygon) {
			setPath(contour);
		}
	}, [contour, map, polygon, setPath]);

	useEffect(() => {
		if (map && polygon) {
			console.log('editing mode', props.allowEdit);
			if (props.allowEdit) {
				polygon.enableEditing();
			} else {
				polygon.disableEditing();
			}
		}
	}, [map, polygon, props.allowEdit])

	useEffect(() => {
		if (divElm.current) {
			// @ts-ignore
			setContainer(divElm.current);
		}
	});

	useEffect(() => {
		if (map) {
			console.log('updating map');
			map.enableScrollWheelZoom();
			if (contour.length > 0 && !props.allowEdit) {
				setCenter(getCenter(contour));
				map.setZoom(10);
			}
		}
	}, [contour, map, props.allowCreation, props.allowEdit, setCenter]);

	useEffect(() => {
		if (props.polygon) {
			setContour(props.polygon);
		}
	}, [props.polygon]);

	return (
		<div ref={divElm} style={{ height: '100%', width: '100%' }} />
	);
}
